package com.example.satoken.validator;

import com.example.satoken.annotion.EnumValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 校验枚举逻辑
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Enum<?>> {

    private Set<String> allowedValues;

    @Override
    public void initialize(EnumValue annotation) {
        Class<? extends Enum<?>> enumClass = annotation.target();
        // 取得枚举类型对象
        Enum<?>[] allowedValues = enumClass.getEnumConstants();
        this.allowedValues = Arrays.stream(allowedValues)
                .map(Enum::name)
                .collect(Collectors.toSet());
    }

    @Override
    public boolean isValid(Enum<?> value, ConstraintValidatorContext context) {
        // 允许值不为: null
        if (value == null) {
            return false;
        }
        // 判断Value是否在枚举范围内
        return allowedValues.contains(value.name());
    }
}